package com.work.daily;

import java.util.LinkedHashMap;

/**
 * 方法二 利用LinkedHashMap,但不重写removeEldestEntry

 * Created by suk on 2020/8/24.
 */
public class LRUCache_16_25_2 {

    LinkedHashMap<Integer, Integer> map;
    int capacity;

    public LRUCache_16_25_2(int capacity) {

        this.capacity = capacity;
        map = new LinkedHashMap<>();
    }

    public int get(int key) {
        if (!map.containsKey(key))
            return -1;
        Integer value = map.remove(key);
        map.put(key, value);
        return value;
    }

    public void put(int key, int value) {
        if (map.containsKey(key)) {
            map.remove(key);
            map.put(key, value);
            return ;
        }
        if (map.size() == capacity)
            map.remove(map.entrySet().iterator().next().getKey());
        map.put(key, value);

        return ;
    }

    public static void main(String[] args) {
        LRUCache_16_25_2 l = new LRUCache_16_25_2(2);
        l.put(1, 2);
        l.put(2, 3);
        l.put(3, 4);
        l.get(2);
    }
}
